<?php

namespace app\admin\controller\product;

use app\common\controller\Backend;

class Unit extends Backend
{
    protected $model = null;
    //关联查询的意思
    protected $relationSearch = true;
    public function __construct()
    {
        parent::__construct();
        $this->model = model("Product.Unit");
    }
    public function index()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count(); //查询总数

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select(); //查询数据
            // echo   $this->SubjectOrderModel->getlastSql();exit;
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    // 添加
    public function add()
    {
        if ($this->request->isAjax()) {
            $params = $this->request->param('row/a');
            $result = $this->model->validate('common/product/Unit')->save($params);
            if ($result === FALSE) {
                $this->error($this->model->getError());
                exit;
            } else {
                $this->success();
                exit;
            }
        }
        return $this->view->fetch();
    }
    // 编辑
    public function edit($ids = null)
    {
        $row = $this->model->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
            exit;
        }
        $this->assign([
            'row' => $row
        ]);
        if ($this->request->isAjax()) {
            $params = $this->request->param('row/a');
            $params['id'] = $ids;
            $result = $this->model->validate('common/product/Unit')->isUpdate(true)->save($params);
            if ($result === FALSE) {
                $this->error($this->model->getError());
                exit;
            } else {
                $this->success();
                exit;
            }
        }
        return $this->view->fetch();
    }
    // 删除
    public function del($ids = null)
    {
        $ids = !empty($ids) ? explode(',', $ids) : [];
        $row = $this->model->column('id');
        foreach ($ids as $item) {
            if (!in_array($item, $row)) {
                $this->error('没有找到该商品单位名称');
                exit;
            }
        }
        $result = $this->model->destroy($ids);
        if ($result === FALSE) {
            $this->error($this->model->getError());
            exit;
        } else {
            $this->success();
            exit;
        }

    }
}